import { defineStore } from 'pinia'
import { ref, watch, computed } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { agencyAsync } from '@/appox/appox'
import { useSignalChooserStore } from './signalChooser'

export const useSignedSignalChooserStore = defineStore('signedSignalChooser', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const searchKey = ref('')
  const treeData = ref([])
  const originSelectedValueId = ref(null)
  const originSelectedSignBitId = ref(null)
  const originScale = ref(null)
  const signalScale = ref(1.0)
  const signalUnit = ref('')
  const signBitSignalId = ref(null)
  const signBitSignalName = ref('')

  // 计算属性
  const showDeleteButton = computed(() => originSelectedValueId.value !== null)
  const showScaleSetting = computed(() => originScale.value !== null)

  async function updateTreeData(key) {
    const signalTree = await agencyAsync.getSignalTree()
    if (!signalTree) {
      treeData.value = []
      return
    }

    const topNodes = []
    const keyLower = key.toLowerCase()
    const keyValid = key.length >= 2

    for (const top of signalTree) {
      const topMatch = keyValid && (top.id.toLowerCase().includes(keyLower) || top.name.toLowerCase().includes(keyLower))
      const topNode = {
        id: top.id,
        name: top.name,
        children: []
      }
      let shouldAddTopNode = !keyValid || topMatch

      if (top.children) {
        for (const middle of top.children) {
          const middleMatch = keyValid && (middle.id.toLowerCase().includes(keyLower) || middle.name.toLowerCase().includes(keyLower))

          const middleNode = {
            id: middle.id,
            name: middle.name,
            children: []
          }
          let shouldAddMiddleNode = !keyValid || topMatch || middleMatch

          if (middle.children) {
            for (const signal of middle.children) {
              const signalMatch = keyValid && (signal.id.toLowerCase().includes(keyLower) || signal.name.toLowerCase().includes(keyLower))
              const isSelected = signal.id === originSelectedValueId.value

              const signalNode = {
                id: signal.id,
                name: signal.name,
                exist: isSelected
              }
              const shouldAddSignalNode = !keyValid || topMatch || middleMatch || signalMatch

              if (shouldAddSignalNode) {
                middleNode.children.push(signalNode)
                shouldAddMiddleNode = true
              }
            }
          }

          if (shouldAddMiddleNode) {
            middleNode.expandChildren = keyValid
            topNode.children.push(middleNode)
            shouldAddTopNode = true
          }
        }
      }

      if (shouldAddTopNode) {
        topNode.expandChildren = keyValid
        topNodes.push(topNode)
      }
    }

    treeData.value = topNodes
  }

  watch(searchKey, (newVal) => {
    const key = newVal ?? ''
    updateTreeData(key)
  })

  // 动作
  function initialize(originValueId = null, originSignBitId = null, originSignalScale = null, unit = '') {
    originSelectedValueId.value = originValueId
    originSelectedSignBitId.value = originSignBitId
    originScale.value = originSignalScale
    signalUnit.value = unit
    signalScale.value = originSignalScale
    signBitSignalId.value = originSignBitId
    searchKey.value = ''
    updateSignBitSignalName()
    updateTreeData('')
  }

  async function updateSignBitSignalName() {
    if (signBitSignalId.value) {
      try {
        const signalName = await agencyAsync.getSignalName(signBitSignalId.value, true)
        signBitSignalName.value = signalName || signBitSignalId.value
      } catch (error) {
        signBitSignalName.value = signBitSignalId.value
      }
    } else {
      signBitSignalName.value = ''
    }
  }

  async function chooseSignBitSignal() {
    const signalChooserStore = useSignalChooserStore()
    const result = await signalChooserStore.show(signBitSignalId.value)
    signBitSignalId.value = result[0]
    updateSignBitSignalName()
  }

  function confirm(signalNode) {
    const signalId = signalNode ? signalNode.id : null
    const result = [signalId, signBitSignalId.value, signalScale.value]
    dialogQueue.hide(result)
  }

  function deleteSignal() {
    dialogQueue.hide([null, null, originScale.value == null ? null : 1.0])
  }

  function cancel() {
    dialogQueue.hide([originSelectedValueId.value, originSelectedSignBitId.value, originScale.value])
  }

  function show(originValueId = null, originSignBitId = null, originSignalScale = null, unit = '') {
    return dialogQueue.show({
      onLoaded: () => initialize(originValueId, originSignBitId, originSignalScale, unit)
    })
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    searchKey,
    treeData,
    originSelectedValueId,
    originSelectedSignBitId,
    originScale,
    signalScale,
    signalUnit,
    signBitSignalId,
    signBitSignalName,
    // 计算属性
    showDeleteButton,
    showScaleSetting,
    // 动作
    initialize,
    chooseSignBitSignal,
    confirm,
    deleteSignal,
    cancel,
    show,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
})
